<?php
// +----------------------------------------------------------------------
// | EtrolPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Author: Author: HCZ <huangchengze@etrol.com> 
// +----------------------------------------------------------------------

namespace app\alarm\controller\ajax;

/**
 * 报警信息
 * @author huangchengze
 *
 */
class Alarm {
	/**
	 * 报警信息列表
	 */
	public function  alarmList () {
		$this->detectAlarm();
		$where =[];
		$hasWhere = [];
		if(input('where') !== null && input('where') !== '*'){
			$where['alarm.status'] = input('where');
		}
		if(input('scope')){
			$hasWhere['enterpriseId'] = input('scope');
		}
		if(($limit = input('limit')) && ($page = input('page'))){
			$startLimit =  ($page-1)*$limit;
		
			$info = collection(model('Alarm')->hasWhere('dangerSource',$hasWhere)->with('dangerSource,dangerSource.enterprise')->where($where)->limit($startLimit.','.$limit)->order('id desc')->select())->toArray();
		}else{
			$info = collection(model('Alarm')->hasWhere('dangerSource',$hasWhere)->with('dangerSource,dangerSource.enterprise')->where($where)->order('id desc')->select())->toArray();
		}
		$count = model('Alarm')->hasWhere('dangerSource',$hasWhere)->with('dangerSource,dangerSource.enterprise')->where($where)->count();
		
		if(empty($info)){
			json(['code'=>0,'msg'=>'没有报警信息','count'=>0,'data'=>$info]);
		}
		return json(['code'=>1,'msg'=>'','count'=>$count,'data'=>$info]);
	}
	
	/**
	 * 传感器详情
	 * @param string $sensorId
	 * @return \think\response\Json
	 */
	public function sensor ($sensorId = null){
		if($sensorId){
			$sensor  = model('Sensor')->with(['dangersource'=>['enterprise','staff']])->find($sensorId)->toArray();
			if(!empty($sensor)){
				return json(['code'=>1,'msg'=>'','data'=>$sensor]);
			}
		}
		return json(['code'=>0,'msg'=>'数据异常','data'=>'']);
	}
	
	private function detectAlarm(){
		$sensors = model('Sensor')->where('status',0)->select();
		if(!empty($sensors)){
			foreach($sensors as $sensor){
				$alarmExist = model('Alarm')->where('sensorId',$sensor['id'])->where('status','in',[0,1])->count();
				if($alarmExist == 0){
					$alarm['title'] = $sensor['title'].' 异常';
					$alarm['sensorId'] = $sensor['id'];
					$alarm['dangerSourceId'] = $sensor['dangerSourceId'];
					model('basic/Dangersource')->where('id',$sensor['dangerSourceId'])->update(['status'=>2]);
					model('Alarm')->save($alarm);
				}
			}
		}
	}
}